package com.yupi.springbootinit.datasource;

import com.yupi.springbootinit.model.enums.SearchTypeEnum;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 注册器模式
 * 将需要使用到的数据源使用map提前注册好，需要使用时直接取
 */
@Component
public class DataRegister {

    @Resource
    private PictureDataSource pictureDataSource;
    @Resource
    private UserDataSource userDataSource;
    @Resource
    private PostDataSource postDataSource;

    private Map<String, DataSource<Object>> typeMap = null;

    //在bean初始化后调用
    @PostConstruct
    public void doInit(){
        typeMap = new HashMap(){{
            put(SearchTypeEnum.USER.getValue(),userDataSource);
            put(SearchTypeEnum.POST.getValue(),postDataSource);
            put(SearchTypeEnum.PICTURE.getValue(),pictureDataSource);
        }};
    }

    public DataSource getDataSourceByType(String type){
        if (typeMap == null) {
            return null;
        }
        return typeMap.get(type);
    }

}
